﻿using System;

namespace Agile.DataAccess
{
    /// <summary>
    /// 
    /// </summary>
    internal partial class DbContext
	{
        /// <summary>
        /// 
        /// </summary>
        /// <param name="useTransaction"></param>
        /// <returns></returns>
		public IDbContext UseTransaction(bool useTransaction)
		{
			Data.UseTransaction = useTransaction;
			return this;
		}
        /// <summary>
        /// 
        /// </summary>
        /// <param name="useSharedConnection"></param>
        /// <returns></returns>
		public IDbContext UseSharedConnection(bool useSharedConnection)
		{
			Data.UseSharedConnection = useSharedConnection;
			return this;
		}
        /// <summary>
        /// 
        /// </summary>
        /// <param name="isolationLevel"></param>
        /// <returns></returns>
		public IDbContext IsolationLevel(IsolationLevel isolationLevel)
		{
			Data.IsolationLevel = isolationLevel;
			return this;
		}
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
		public IDbContext Commit()
		{
			TransactionAction(() => Data.Transaction.Commit());
			return this;
		}
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
		public IDbContext Rollback()
		{
			TransactionAction(() => Data.Transaction.Rollback());
			return this;
		}

		private void TransactionAction(Action action)
		{
			if(Data.Transaction == null)
				return;
			if(!Data.UseTransaction)
				throw new FluentDataException("Transaction support has not been enabled.");
			action();
			Data.Transaction = null;
		}
	}
}
